use std::{
	fs::File,
	io::{BufRead, BufReader},
	sync::{Arc, Mutex},
};

use crate::{
	core::cluster::{Cluster, CLUSTERS},
	error, info,
	utils::file_dir::makesure_dir,
	warn,
};
use lazy_static::lazy_static;

lazy_static! {
	pub static ref CONFIG_PATH: Arc<Mutex<String>> = Arc::new(Mutex::new(String::new()));
	pub static ref DATA_PATH: Arc<Mutex<String>> = Arc::new(Mutex::new(String::new()));
	pub static ref TOKEN: Arc<Mutex<String>> = Arc::new(Mutex::new(String::new()));
}

pub fn init_config() {
	info!(format!(
		"Initializing config at: {}",
		CONFIG_PATH.lock().unwrap()
	));

	let path_str = DATA_PATH.lock().unwrap().clone();
	makesure_dir(&path_str);

	let file = File::open(CONFIG_PATH.lock().unwrap().as_str()).unwrap();
	let reader = BufReader::new(file);

	let mut cluster_name = String::from("default");
	CLUSTERS.lock().unwrap().insert(
		"default".to_string(),
		Cluster {
			name: "default".to_string(),
			files: Vec::new(),
		},
	);

	for line in reader.lines() {
		let content = line.unwrap();
		let mut content_without_spaces = content.clone();
		content_without_spaces.retain(|c| c != ' ');

		// 忽略空行
		if content_without_spaces.len() == 0 {
			continue;
		}

		// 判断 TOKEN = ***
		if content_without_spaces.starts_with("TOKEN=") {
			let mut token = TOKEN.lock().unwrap();
			*token =
				content_without_spaces["TOKEN=".len()..content_without_spaces.len()].to_string();
			continue;
		}

		// 判断 [cluster_name]
		if content.starts_with('[') && content.ends_with(']') {
			cluster_name = content[1..content.len() - 1].to_string();
			CLUSTERS.lock().unwrap().insert(
				cluster_name.clone(),
				Cluster {
					name: cluster_name.clone(),
					files: Vec::new(),
				},
			);
			continue;
		}

		// 若不为以上任何情况，则为一行路径
		match CLUSTERS.lock().unwrap().get_mut(&cluster_name) {
			Some(cluster) => cluster.files.push(content),
			None => {
				error!(format!("Invalid cluster name: {}", cluster_name));
			}
		}
	}

	if TOKEN.lock().unwrap().len() == 0 {
		warn!("TOKEN is empty. Make sure your internet env is credible.");
	}
}
